package yana.tpe.onlineshop.domain.domains;

import java.io.Serializable;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.LazyInitializationException;

/**
 *
 */
@Entity(name = "category")
@Table(name = "category")
public class Category  implements AbstractEntity<Integer>, Serializable {

    @Id
    @GeneratedValue
    private Integer id;

    @Column(name = "name")
    private String name;

    @ManyToOne
    private Category parent;

    @OneToMany(cascade=CascadeType.ALL, mappedBy = "parent")
    private Set<Category> childs = new HashSet<Category>();

    @OneToMany(cascade=CascadeType.ALL, mappedBy = "category")
    private Set<Product> products = new HashSet<Product>();

    public Category() {
    }

    public Category(String name, Category parent) {
        this.name = name;
        this.parent = parent;
    }

    @Override
    public Integer getId() {
        return id;
    }

    @Override
    public void setId(Integer id) {
        this.id = id;
    }

    public Set<Category> getChilds() {
//        try {
//            childs.iterator();
            return childs;
//        } catch (LazyInitializationException ex) {
//            return Collections.emptySet();
//        }
    }

    public void setChilds(Set<Category> childs) {
        this.childs = childs;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Category getParent() {
        return parent;
    }

    public void setParent(Category parent) {
        this.parent = parent;
    }

    public Set<Product> getProducts() {
        try {
            products.iterator();
            return products;
        } catch (LazyInitializationException ex) {
            return Collections.emptySet();
        }
    }

    public void setProducts(Set<Product> products) {
        this.products = products;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final Category other = (Category) obj;
        if (this.id != other.id && (this.id == null || !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public int hashCode() {
        int hash = 7;
        hash = 43 * hash + (this.id != null ? this.id.hashCode() : 0);
        return hash;
    }

    @Override
    public String toString() {
        return "Category{" + "id=" + id + "; name=" + name + '}';
    }

}
